Skip to content

fix(parse): apply array type transform once per parse - #182

Open
shaurya703 wants to merge 1 commit into
cacjs:mainfrom
shaurya703:fix/apply-type-once
Open

shaurya703 wants to merge 1 commit into
cacjs:mainfrom
shaurya703:fix/apply-type-once

Conversation

@shaurya703

Copy link
Copy Markdown

Bug

An option declared with type: [fn] has fn applied more than once when other options are also passed:

cli
  .option('-c, --color <hex>', 'Color as hex', {
    type: [(v) => Number.parseInt(v, 16)],
  })
  .option('--verbose', 'Verbose output')

cli.parse('node bin --color ff --verbose'.split(' ')).options.color
// expected [255], got [1431]

Dot-nested values on an array-typed option are also lost after the first one:

cli.option('--env <env>', 'Set env', { type: [] })
cli.parse('node bin --env.a 1 --env.b 2'.split(' ')).options.env
// expected [{ a: 1, b: 2 }], got [{ a: 1 }]

Cause

In CAC#mri, setByType(options, transforms) is called inside the loop over parsed keys. Once the option has a value, every later iteration wraps it with [x].flat() again and re-maps it through the transform. Number-like transforms such as Number are idempotent so this goes unnoticed, but any other transform is applied once per remaining key (aliases like c/color count as separate keys).

For dot-nested options, the value is turned into an array after the first key, so the next setDotProp for env.b writes b onto the array rather than onto the object inside it.

Fix

Call setByType once, after the loop has set every value.

One side effect: an option whose default is set and that has type is now always transformed. Before, its default was transformed only when some other option happened to be passed (node bin gave the raw default, node bin --verbose gave the transformed one), so the result is now the same either way.

Tests

Added two tests in tests/index.test.ts, one per case above. Both fail on main ([1431], and b missing) and pass with the fix. pnpm vitest run (23 passed), pnpm lint and pnpm typecheck are clean.

setByType ran inside the loop over parsed keys, so a type transform was
re-applied once per remaining key (aliases included), and wrapping a
dot-nested option in an array mid-loop made later keys like `--env.b`
land on the array instead of the object.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant